math.randomseed(os.time())
local genid = {}

function genid.gen(red)
    local min = 100001
    local max = 999999
    local script = [[
        local k = ARGV[1]
        local r = ARGV[2]
        local v = redis.call('exists',k)
        if v==1 then
            return nil
        end
        redis.call('set',k,r)
        return r
    ]]
    while true do
        local r = math.random(min, max)
        local k = string.format("%s-useruid-%d", APPNAME, r)
        local a = red:eval(script, 2, "k", "r", k, r)
        if a then
            return r
        end
    end
end

function genid.genyardid(red)
    local min = 100001
    local max = 999999
    local script = [[
        local k = ARGV[1]
        local r = ARGV[2]
        local v = redis.call('exists',k)
        if v==1 then
            return nil
        end
        redis.call('set',k,r)
        return r
    ]]
    while true do
        local r = math.random(min, max)
        local k = string.format("%s-yardid-%d", APPNAME, r)
        local a = red:eval(script, 2, "k", "r", k, r)
        if a then
            return r
        end
    end
end

function genid.genhallid(red)
    local min = 100001
    local max = 999999
    local script = [[
        local k = ARGV[1]
        local r = ARGV[2]
        local v = redis.call('exists',k)
        if v==1 then
            return nil
        end
        redis.call('set',k,r)
        return r
    ]]
    while true do
        local r = math.random(min, max)
        local k = string.format("%s-hallid-%d", APPNAME, r)
        local a = red:eval(script, 2, "k", "r", k, r)
        if a then
            return r
        end
    end
end

function genid.genhallid(red)
    local min = 100001
    local max = 999999
    local script = [[
        local k = ARGV[1]
        local r = ARGV[2]
        local v = redis.call('exists',k)
        if v==1 then
            return nil
        end
        redis.call('set',k,r)
        return r
    ]]
    while true do
        local r = math.random(min, max)
        local k = string.format("%s-hallid-%d", APPNAME, r)
        local a = red:eval(script, 2, "k", "r", k, r)
        if a then
            return r
        end
    end
end

function genid.genotherid(red)
    local k = string.format("%s-genotherid", APPNAME)
    return red:incr(k)
end


return genid
